//
//  WWRequestService.m
//  WangLottery
//
//  Created by 黄修勇 on 12-9-10.
//
//

#import "WWRequestService.h"
#import "Reachability.h"

@implementation WWRequestService

@synthesize netWorkEabled=_netWorkEabled;


-(WWRequestNetType)checkNetWork{

    Reachability* wifi = [Reachability reachabilityForLocalWiFi];
    [wifi startNotifier];
    NetworkStatus netStatus = [wifi currentReachabilityStatus];
    if (netStatus==NotReachable) {
        Reachability *internet=[Reachability reachabilityForInternetConnection];
        [internet startNotifier];
        netStatus=[internet currentReachabilityStatus];
        if (netStatus==NotReachable) {
            _netWorkEabled=YES;
            return WWRequestNetTypeNone;
        }else{
            _netWorkEabled=NO;
            return WWRequestNetTypeWIFI;
        }
    }else
    {
        _netWorkEabled=NO;
        return WWRequestNetType3G;
    }
}

-(ASIFormDataRequest *)postFormRequestWithURL:(NSString *)url params:(NSDictionary *)paraDic target:(id<ASIHTTPRequestDelegate>)delegate timeOut:(NSTimeInterval)time error:(NSError **)error{

    
    if ([self checkNetWork]==WWRequestNetTypeNone) {
        if (!*error) {
            NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:@"当前网络不可用",NSLocalizedDescriptionKey, nil];
            *error=[NSError errorWithDomain:@"WWRequest" code:100 userInfo:dic];
            return nil;
        }
    }
    
    CLog(@"host %@",url);
    
    NSString *enHost=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *requestURL=[NSURL URLWithString:enHost];
    if (!requestURL) {
        if (!*error) {
            NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:@"请求地址错误",NSLocalizedDescriptionKey, nil];
            *error=[NSError errorWithDomain:@"WWRequest" code:101 userInfo:dic];
            return nil;
        }
    }
    
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:requestURL];
    request.timeOutSeconds=time;
    [request setStringEncoding:NSUTF8StringEncoding];
    request.delegate=delegate;
    [request setRequestMethod:@"POST"];
    
    for (NSString *key in paraDic) {
        [request setPostValue:[paraDic objectForKey:key] forKey:key];
    }
    [request startAsynchronous];
    return request;
}
@end
